#include "game_widget.h"
#include <QPaintEvent>
#include <QPainter>
#include <QObject>
#include "table_item.h"
using namespace dymy;
FrameLayout::FrameLayout(QWidget *parent):QLayout(parent),children(){}

void FrameLayout::addWidget(QWidget *w, Qt::Alignment alignment){
    QWidgetItem *item =new QWidgetItem(w);
    item->setAlignment( alignment);
    children.append(item);
}

void FrameLayout::setGeometry(const QRect &rect){
    doLayout(rect);

    QLayout::setGeometry(rect);
}

QSize FrameLayout::sizeHint() const{
    const int c = count();
    if(c>0)
    {
        QSize maxSizeHit = itemAt(0)->sizeHint();
        for(int i =1;i<c;++i)
        {
            QSize currSizeHit = itemAt(i)->sizeHint();
            if(currSizeHit.width()>maxSizeHit.width())
            {
                maxSizeHit = maxSizeHit.expandedTo(currSizeHit);
            }
        }
        return maxSizeHit;
    }
    else
    {
        return QSize(100,100);
    }

}

QSize FrameLayout::minimumSize() const{
    const int c = count();
    if(c>0)
    {
        QSize maxSizeHit = itemAt(0)->minimumSize();
        for(int i =1;i<c;++i)
        {
            QSize currSizeHit = itemAt(i)->minimumSize();
            if(currSizeHit.width()>maxSizeHit.width())
            {
                maxSizeHit = maxSizeHit.expandedTo(currSizeHit);
            }

        }
        return maxSizeHit;
    }
    else
    {
        return QSize(100,100);
    }
}

void FrameLayout::addItem(QLayoutItem *item){
    children.push_back(item);
}

QLayoutItem *FrameLayout::itemAt(int index) const{
    return children.value(index);
}

QLayoutItem *FrameLayout::takeAt(int index){
    return children.takeAt(index);
}

int FrameLayout::count() const{
    return children.size();
}

FrameLayout::~FrameLayout(){
    qDeleteAll(children);

}

void FrameLayout::doLayout(const QRect &rect)
{
    const int c = count();

    for(int i =0;i<c;++i)
    {
        QLayoutItem *item = itemAt(i);

        QSize item_size = item->sizeHint();

        QRect item_rect(0,0,item_size.width(),item_size.height());


        switch (item->alignment()&Qt::AlignHorizontal_Mask) {
        case Qt::AlignHCenter:
            item_rect.translate((rect.width()-item_size.width())/2,0);
            break;
        case Qt::AlignLeft:
            item_rect.translate(0,0);
            break;
        case Qt::AlignRight:
            item_rect.translate(rect.width()-item_size.width(),0);
            break;
        }

        switch (item->alignment()&Qt::AlignVertical_Mask) {
        case Qt::AlignVCenter:
            item_rect.translate(0,(rect.height()-item_size.height())/2);
            break;
        case Qt::AlignTop:
            item_rect.translate(0,0);
            break;
        case Qt::AlignBottom:
            item_rect.translate(0,rect.height()-item_size.height());
            break;
        }
        item->setGeometry(item_rect);
    }
}

CardPlayWidget::CardPlayWidget(QWidget *parent):QWidget(parent){
    set_cards(QVector<CARD_t>());
}

QVector<CARD_t> CardPlayWidget::get_selected_cards()
{
    QVector<CARD_t> r;

    for (int i=0;i<cards.size();++i) {
        CARD_t &c = cards[i];
        if(cards_selected[i])
        {
            r.push_back(c);
        }
    }
    return r;
}

QSize CardPlayWidget::minimumSizeHint() const{
    return total_width_size;
}

QSize CardPlayWidget::sizeHint() const{
    return total_width_size;
}

void CardPlayWidget::clear_cards()
{
    cards.clear();
    cards_selected.clear();
    calc_size();
    updateGeometry();
    update();
}

void CardPlayWidget::set_cards(const QVector<CARD_t> &c)
{
    cards = c;
    cards_selected = QVector<bool>(c.size(),false);
    calc_size();
    updateGeometry();
    update();
}

void CardPlayWidget::setCardSize(int width, int height, int showWidth)
{
    card_width = width;
    card_height = height;
    show_width = showWidth;
}

void CardPlayWidget::mouseReleaseEvent(QMouseEvent *event){
    const int cards_size = cards.size();

    if(cards_size>0)
    {
        int total_width = card_width+show_width*(cards_size-1);
        const QRect screen = rect();
        const int total_card_height = card_height+selected_top_height;
        const int start_x_last = screen.width()-((screen.width()-total_width)*0.5)-card_width;
        const int start_y = (screen.height()-total_card_height)*0.5;
        QRect card_rect(start_x_last,start_y,card_width,card_height);

        int i=cards_size-1;
        do{
            if(!cards_selected[i])
            {
                card_rect.translate(0,selected_top_height);
            }

            if(card_rect.contains(event->x(),event->y()))
            {

                if(!cards_selected[i])
                {
                    cards_selected[i]=true;
                }
                else
                {
                    cards_selected[i] = false;
                }
                update();
                break;
            }

            if(!cards_selected[i])
            {
                card_rect.translate(0,-selected_top_height);
            }

            --i;
            //向右移动，用于绘制下一张牌;
            card_rect.translate(-show_width,0);
        }while(i>=0);
    }

}

QString CardPlayWidget::to_card_num(CARD_t card)
{
    switch (decode_card_num(card)) {
    case 0:
        return "3";
    case 1:
        return "4";
    case 2:
        return "5";
    case 3:
        return "6";
    case 4:
        return "7";
    case 5:
        return "8";
    case 6:
        return "9";
    case 7:
        return "10";
    case 8:
        return "J";
    case 9:
        return "Q";
    case 10:
        return "K";
    case 11:
        return "A";
    case 12:
        return "2";
    case 13:
        return "king";
    case 14:
        return "KING";
    default:
        return "";
    }

    return QString::number(card);
}

void CardPlayWidget::to_card_type(CARD_t card, QString &type, QColor &color)
{
    switch (dymy::decode_card_type(card)) {
    case SPADE:
        type = "♠";
        color = QColor(0xff000000);
        break;
    case HEART:
        type = "♥";
        color = QColor(0xffFF0000);
        break;
    case DIAMOND:
        type = "♦";
        color = QColor(0xffFF0000);
        break;
    case CLUB:
        type = "♣";
        color = QColor(0xff000000);
        break;
    default:
        type = "";
        color = QColor(0xff000000);
        break;
    }
}

void CardPlayWidget::paintEvent(QPaintEvent *event){
    const int cards_size = cards.size();

    if(cards_size>0)
    {

        int total_width = card_width+show_width*(cards_size-1);

        const QRect screen = rect();
        const int total_card_height = card_height+selected_top_height;
        const int start_x = (screen.width()-total_width)*0.5;
        const int start_y = (screen.height()-total_card_height)*0.5;
        QRect card_rect(start_x,start_y,card_width,card_height);

        int i=0;

        QString type_text;
        QColor type_color;

        do{
            if(!cards_selected[i])
            {
                //如果没选中，绘制的时候需要往下移动
                card_rect.translate(0,selected_top_height);
            }

            QPainter bg_painter(this);
            QBrush bg_brush(0xffffffff);
            bg_painter.setBrush(bg_brush);

            bg_painter.drawRect(card_rect);

            QPainter painter(this);
            QBrush brushRect(QColor(0xffffffff));


            to_card_type(cards[i],type_text,type_color);
            painter.setPen(type_color) ;

            painter.drawText(card_rect.left()+3,card_rect.top()+2,card_rect.width(),card_rect.height(),Qt::AlignLeft,to_card_num(cards[i]));

            if(type_text.length()>0)
            {
               painter.drawText(card_rect.left()+2,card_rect.top()+10,card_rect.width(),card_rect.height(),Qt::AlignLeft,type_text);
            }

            if(!cards_selected[i])
            {
                //绘制完成后需要哦还原
                card_rect.translate(0,-selected_top_height);
            }

            ++i;
            //向右移动，用于绘制下一张牌;
            card_rect.translate(show_width,0);
        }while(i<cards_size);
    }
}

void CardPlayWidget::calc_size()
{
    total_width_size.setHeight(card_height+selected_top_height);

    if(cards.size()>0)
    {
        int total_width = card_width+show_width*(cards.size()-1);
        total_width_size.setWidth(total_width);
    }
    else
    {
        total_width_size.setWidth(0);
    }
}

TableSelfWidget::TableSelfWidget(QWidget *parent):QWidget(parent),user_info(){

    layout_container = new QVBoxLayout(this);

    max_card_widget = new CardPlayWidget(this);
    max_card_widget->setEnabled(false);
    layout_container->addWidget(max_card_widget);

    layout_info = new QHBoxLayout();
    layout_info->addStretch();
    label_user_name = new QLabel(this);
    layout_info->addWidget(label_user_name);

    label_prepare = new QLabel(this);
    layout_info->addWidget(label_prepare);

    label_role = new QLabel(this);
    layout_info->addWidget(label_role);

    label_cards_num = new QLabel(this);
    layout_info->addWidget(label_cards_num);

    label_status = new QLabel(this);
    layout_info->addWidget(label_status);
    layout_info->addStretch();

    layout_container->addLayout(layout_info);

    layout_operation = new QHBoxLayout();
    layout_operation->addStretch();

    button_prepare = new QPushButton(this);
    button_prepare->setText(tr("准备"));
    connect(button_prepare,&QPushButton::clicked,[=](bool){
        emit prepare_clicked(true);
    });
    layout_operation->addWidget(button_prepare);


    button_rob = new QPushButton(this);
    button_rob->setText(tr("抢地主"));
    connect(button_rob,&QPushButton::clicked,[=](bool){
        emit rob_clicked(true);
    });
    layout_operation->addWidget(button_rob);

    button_no_rob = new QPushButton(this);
    button_no_rob->setText(tr("不抢"));
    connect(button_no_rob,&QPushButton::clicked,[=](bool){
        emit rob_clicked(false);
    });
    layout_operation->addWidget(button_no_rob);

    button_cards = new QPushButton(this);
    button_cards->setText("出牌");
    connect(button_cards,&QPushButton::clicked,[=](bool){
        QVector<CARD_t> t = card_play->get_selected_cards();
        emit cards_clicked(t);
    });
    layout_operation->addWidget(button_cards);

    button_no_cards = new QPushButton(this);
    button_no_cards->setText("不出");
    connect(button_no_cards,&QPushButton::clicked,[=](bool){
        emit no_cards_clicked();
    });
    layout_operation->addWidget(button_no_cards);
    layout_operation->addStretch();
    layout_container->addLayout(layout_operation);

    card_play = new CardPlayWidget(this);
    layout_container->addWidget(card_play);

    setUserInfo(user_info);
}

void TableSelfWidget::setUserInfo(const TableUser * const &user, const QVector<CARD_t> &max_cards)
{
    user_info = user;
    if(user&&user->user_id>0)
    {
        max_card_widget->set_cards(user->played_cards);

        label_user_name->setText(user_info->name);
        label_prepare->setText(user_info->prepared?tr("已准备"):tr("未准备"));

        if(user_info->role==1)
        {
            label_role->setText(tr("地主"));

        }
        else if(user_info->role==0)
        {
            label_role->setText(tr("农民"));
        }
        else
        {
            label_role->setText(tr(""));
        }
        label_cards_num->setText(QString("剩余:%1").arg(user_info->cards.size()));
        if(!user->prepared)
        {
            button_prepare->setVisible(true);
            button_rob->setVisible(false);
            button_no_rob->setVisible(false);
            button_cards->setVisible(false);
            button_no_cards->setVisible(false);
        }
        else
        {
            switch (user_info->status) {
            case PERSON_STEP_WAITING:
                //刚进入房间，无状态
                label_status->setText("");
                button_prepare->setVisible(false);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            case PERSON_STEP_ALLOT_WAITING:
                //抢地主，但还没轮到你
                label_status->setText("");
                button_prepare->setVisible(false);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            case PERSON_STEP_ALLOT_PROCESS:
                //正在轮到你抢地主
                label_status->setText("");
                button_prepare->setVisible(false);
                button_rob->setVisible(true);
                button_no_rob->setVisible(true);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            case PERSON_STEP_ALLOT_REJECT:
                //你没抢地主
                label_status->setText("不抢");
                button_prepare->setVisible(false);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            case PERSON_STEP_PLAING:
                //你开始出牌
                label_status->setText("");

                button_prepare->setVisible(false);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(true);
                button_no_cards->setVisible(true);
                break;
            case PERSON_STEP_PLAING_WAITING:
                //还没轮到你出牌
                label_status->setText(tr(""));
                button_prepare->setVisible(false);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            case PERSON_STEP_PLAING_NOT_AFFORD:
                //你要不起
                label_status->setText("不要");
                button_prepare->setVisible(false);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            case PERSON_STEP_PLAING_YET:
                //你出过牌了（存下你的牌）
                label_status->setText("");
                button_prepare->setVisible(false);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            case PERSON_STEP_FINISHED_SUCCESS:
                //你胜利了
                label_status->setText(tr("你胜利了"));
                button_prepare->setVisible(true);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            case PERSON_STEP_FINISHED_FAILED:
                //你失败了
                label_status->setText(tr("你失败了"));
                button_prepare->setVisible(true);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            default:
                label_status->setText(tr(""));
                button_prepare->setVisible(false);
                button_rob->setVisible(false);
                button_no_rob->setVisible(false);
                button_cards->setVisible(false);
                button_no_cards->setVisible(false);
                break;
            }
        }
        card_play->set_cards(user_info->cards);
    }
    else
    {
        max_card_widget->clear_cards();
        label_user_name->setText(tr("暂无玩家"));
        label_prepare->setText("");
        label_role->setText("");
        label_cards_num->setText("");
        label_status->setText("");
        card_play->set_cards(QVector<CARD_t>());
    }
}

void TableOtherUserWidget::set_hit_visible(bool visible){
    widget_hit->setVisible(visible);
}

TableOtherUserWidget::TableOtherUserWidget(QWidget *parent):QWidget(parent),user_info(){
    layout_out = new QVBoxLayout(this);
    layout_container = new QHBoxLayout();
    layout_info = new QVBoxLayout();
    label_user_name = new QLabel(this);
    layout_info->addWidget(label_user_name);

    label_prepare = new QLabel(this);
    layout_info->addWidget(label_prepare);

    label_role = new QLabel(this);
    layout_info->addWidget(label_role);

    label_cards_num = new QLabel(this);
    layout_info->addWidget(label_cards_num);


    label_status = new QLabel(this);
    layout_info->addWidget(label_status);

    layout_container->addLayout(layout_info);

    max_card_widget = new CardPlayWidget(this);
    layout_container->addWidget(max_card_widget);

    layout_out->addLayout(layout_container);

    widget_hit = new QWidget(this);

    widget_hit->setStyleSheet("QWidget{background-color:red;border-radius:12px;}");

    widget_hit->setMinimumSize(QSize(25,25));
    widget_hit->setMaximumSize(QSize(25,25));
    layout_out->addWidget(widget_hit);

    setUserInfo(user_info);
}

void TableOtherUserWidget::setUserInfo(const TableUser * const &user, const QVector<CARD_t> &max_cards)
{
    user_info = user;

    if(user&&user->user_id>0)
    {
        max_card_widget->set_cards(user->played_cards);

        label_user_name->setText(user_info->name);
        label_prepare->setText(user_info->prepared?tr("已准备"):tr("未准备"));

        if(user_info->role==1)
        {
            label_role->setText(tr("地主"));

        }
        else if(user_info->role==0)
        {
            label_role->setText(tr("农民"));
        }
        else
        {
            label_role->setText(tr(""));
        }
        switch (user_info->status) {
        case PERSON_STEP_WAITING:
            //刚进入房间，无状态
            label_status->setText(tr(""));
            set_hit_visible(false);
            break;
        case PERSON_STEP_ALLOT_WAITING:
            //抢地主，但还没轮到你
            label_status->setText(tr(""));
            set_hit_visible(false);
            break;
        case PERSON_STEP_ALLOT_PROCESS:
            //正在轮到你抢地主
            label_status->setText(tr(""));
            set_hit_visible(true);
            break;
        case PERSON_STEP_ALLOT_REJECT:
            //你没抢地主
            label_status->setText(tr("不抢"));
            set_hit_visible(false);
            break;
        case PERSON_STEP_PLAING:
            //你开始出牌
            label_status->setText(tr(""));
            set_hit_visible(true);
            break;
        case PERSON_STEP_PLAING_WAITING:
            //还没轮到你出牌
            label_status->setText(tr(""));
            set_hit_visible(false);
            break;
        case PERSON_STEP_PLAING_NOT_AFFORD:
            //你要不起
            label_status->setText(tr("不要"));
            set_hit_visible(false);
            break;
        case PERSON_STEP_PLAING_YET:
            //你出过牌了（存下你的牌）
            label_status->setText(tr(""));
            set_hit_visible(false);
            break;
        case PERSON_STEP_FINISHED_SUCCESS:
            //你胜利了
            label_status->setText(tr("胜利"));
            set_hit_visible(false);
            break;
        case PERSON_STEP_FINISHED_FAILED:
            //你失败了
            label_status->setText(tr("失败"));
            set_hit_visible(false);
            break;
        default:
            label_status->setText(tr(""));
            break;
        }

        label_cards_num->setText(QString("剩余:%1").arg(user_info->cards.size()));
    }
    else
    {
        max_card_widget->clear_cards();
        label_user_name->setText(tr("暂无玩家"));
        label_prepare->setText("");
        label_role->setText("");
        label_cards_num->setText("");
        label_status->setText(tr(""));
        set_hit_visible(false);
    }
}


